package com.codefish.codefishseckill.mq;

import com.alibaba.fastjson.JSON;
import com.codefish.codefishseckill.config.RabbitMQConfig;
import com.codefish.codefishseckill.entity.Order;
import com.codefish.codefishseckill.service.OrderService;
import com.codefish.codefishseckill.service.SecKillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 描述
 *
 * @author codefish
 * @version 1.0
 * @date 2022/07/20 下午 03:16
 */
@Component
@Slf4j
public class MQListener {
    @Autowired
    OrderService orderService;
    @Autowired
    SecKillGoodsService secKillGoodsService;

    @Transactional
    @RabbitListener(queues = RabbitMQConfig.ORDER_QUEUE_NAME)
    public void doWithOrderMessage(Message message) throws Exception {
        String orderStr = new String(message.getBody());
        Order order = JSON.parseObject(orderStr, Order.class);
        log.info("收到订单消息：{}。将持久化到数据库", orderStr);

        //首先查看数据库是否已存在订单
        List<Order> orderList = orderService.selectOrderByCondition(order.getUserId(), order.getGoodsId());
        if (orderList != null && !orderList.isEmpty()) {
            log.info("数据库已存在订单信息{},订单消息{}将被丢弃", orderList.get(0), orderStr);
            return;
        }
        //减库存
        secKillGoodsService.updateStockV2(order.getGoodsId(), 1);
        //保存订单消息
        orderService.save(order);
        log.info("订单消息{}已持久化", orderStr);

        //休眠1s
        Thread.sleep(1000);
    }
}
